import { ParseArrayPipe, ParseFilePipe, UploadedFile, UseInterceptors } from '@nestjs/common';
/*
 * @Author: c
 * @Date: 2024-01-15 16:12:27
 * @LastEditTime: 2024-03-17 21:28:54
 * @LastEditors: c
 * @Description: 操作minio
 * @FilePath: \music-web-backend\src\core\system\minio\minio.controller.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Body, Controller, Delete, Get, Param, Post, Put, Query, Req } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request } from 'express';
import { MinioService } from 'nestjs-minio-client';
import { FileDescDto, ResourceType } from './dto/create-file.dto';
import { BucketItemFromList } from './dto/search-minio.dto';
import { MinioClientService } from './minio.service';
// const Ffmpeg = require('fluent-ffmpeg')
const Ffmpeg = require('./ffmpeg')
// import * as Ffmpeg from 'fluent-ffmpeg';
import { Stream } from 'stream';

@Controller('minio')
export class MinioClientController {
  constructor(
    private readonly minioClientService: MinioClientService,
    private readonly minioService: MinioService
  ) { }



  @Get()
  findAll() {
    return this.minioClientService.findAll();
  }

  @Get("listBuckets")
  async listBuckets(): Promise<BucketItemFromList[]> {


    const data = await this.minioService.client.listBuckets();
    return data
  }

  @Get('getPresignedUrl')
  getPresignedUrl(@Req() req: Request, @Query() file: FileDescDto): Promise<any> {
    return this.minioClientService.getPresignedUrl(req, file);
  }




  /**
   * 文件-根据名称-获取上传链接
   * @param req 
   * @param fileName 
   * @param isPublic 
   * @returns 
   */
  @Get('getPresignedUrlByName')
  getPresignedUrlByName(@Req() req: Request, @Query() { fileName, isPublic }: any): Promise<any> {
    var flag = isPublic === "false" ? false : true;
    return this.minioClientService.getPresignedUrlByName(req, fileName, flag);
  }


  @Put("updateFile")
  update(@Req() req: Request, @Body() updateMinioDto: FileDescDto) {
    return this.minioClientService.update(req, updateMinioDto);
  }

  @Delete('deleteFile')
  remove(@Req() req: Request, @Body() file: FileDescDto) {

    return this.minioClientService.remove(req, file);
  }



  /**
   * 文件-根据id-删除
   * @param id 
   */
  @Delete('deleteById/:id')
  deleteFileById(@Param('id') id: string) {

    return this.minioClientService.deleteFileById(id);
  }
  /**
   * 文件-根据id数组-删除
   * @param id 
   */
  @Delete('deleteByIds/:ids')
  deleteFileByIds(@Param('ids', ParseArrayPipe) ids: string[]) {

    return this.minioClientService.deleteFileByIds(ids);
  }


  /**
   * 文件-上传
   * @param req 
   * @param file 
   * @returns 
   */
  @Post()
  @UseInterceptors(FileInterceptor('file'))
  upload(@Req() req: Request, @UploadedFile(new ParseFilePipe({
    validators: [
      // new MaxFileSizeValidator({ maxSize: 1000 }),
      // new FileTypeValidator({ fileType: 'image/jpeg' }),
    ],
  }),) file: Express.Multer.File, @Body() { isPublic = false }: ResourceType) {

    return this.minioClientService.create(req, file, isPublic); //必须return 不然报错终止整个运行的进程
  }
  /**
   * 文件-上传
   * @param req 
   * @param file 
   * @returns 
   */
  @Post("video")
  @UseInterceptors(FileInterceptor('file'))
  async uploadVideo(@Req() req: Request, @UploadedFile(new ParseFilePipe({
    validators: [
      // new MaxFileSizeValidator({ maxSize: 1000 }),
      // new FileTypeValidator({ fileType: 'image/jpeg' }),
    ],
  }),) file: Express.Multer.File) {



    // 方式二：创建文件读取流
    // const inputStream = fs.createReadStream('./test.mp4')
    // fs.createReadStream()
    const bufferStream = new Stream.PassThrough();
    const streams = bufferStream.end(file.buffer);


    // const { originalname, buffer } = file;
    // const streamableObject = new StreamableFile(buffer)
    // const readStream = streamableObject.getStream()
    // const out = await new Converter().wcam265ToMp4(buffer, "test")
    // var command = Ffmpeg("src/core/system/minio/test.mp4")
    //   // const inputStream = fs.createReadStream('src/core/system/minio/test.mp4')
    //   // const outStream = fs.createWriteStream('src/core/system/minio/test2.mp4')
    //   // var command = Ffmpeg()
    //   // .input(inputStream)
    //   .addOutputOption('-movflags', 'frag_keyframe+empty_moov')
    //   .toFormat("mp4")
    //   .size('640x480')
    //   .on("progress", function (progress) {

    //     const { currentFps, currentKbps, frames, targetSize, timemark } = progress
    //     console.log(`currentFps:${currentFps},currentKbps:${currentKbps},frames:${frames},targetSize:${targetSize},timemark:${timemark}`)

    //   })
    //   .on("error", function (err) {
    //     console.log("An error occurred: " + err.message);
    //   })
    //   .on("end", function () {
    //     console.log("Processing finished !");
    //   })
    //   .save(
    //     "src/core/system/minio/test2.mp4"
    //   );



    return this.minioClientService.create(req, file, false); //必须return 不然报错终止整个运行的进程
  }

}





